<template>
    <div class="forum-container">
        <!-- 顶部搜索栏 -->
        <div class="search-bar">
            <input v-model="searchKeyword" placeholder="搜索帖子..." @keyup.enter="handleSearch">
            <button @click="handleSearch">搜索</button>
        </div>

        <!-- 板块列表 -->
        <div class="category-list">
            <h3>论坛板块</h3>
            <ul>
                <li v-for="category in categories" :key="category.id"
                    :class="{ active: currentCategoryId === category.id }" @click="switchCategory(category.id)">
                    {{ category.name }}
                </li>
            </ul>
        </div>

        <!-- 帖子列表 -->
        <div class="post-list">
            <div class="post-list-header">
                <h3>帖子列表</h3>
                <button @click="createNewPost">发布新帖</button>
            </div>
            <ul>
                <li v-for="post in posts" :key="post.id">
                    <div class="post-title">
                        <router-link :to="{ name: 'PostDetail', params: { id: post.id } }">{{ post.title
                            }}</router-link>
                        <span v-if="post.isTop" class="top-tag">置顶</span>
                    </div>
                    <div class="post-meta">
                        <span>作者: {{ post.userName }}</span>
                        <span>板块: {{ post.categoryName }}</span>
                        <span>发布时间: {{ formatDate(post.createTime) }}</span>
                        <span>阅读: {{ post.viewCount }}</span>
                        <span>回复: {{ post.replyCount }}</span>
                        <span>点赞: {{ post.likeCount }}</span>
                    </div>
                    <div class="post-actions">
                        <button @click="toggleLike(post.id, post.isLiked)">{{ post.isLiked ? '取消点赞' : '点赞' }}</button>
                        <button @click="toggleFavorite(post.id, post.isFavorited)">{{ post.isFavorited ? '取消收藏' : '收藏'
                            }}</button>
                    </div>
                </li>
            </ul>
            <div class="pagination" v-if="totalPages > 1">
                <button @click="changePage(1)" :disabled="currentPage === 1">首页</button>
                <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
                <span>{{ currentPage }}/{{ totalPages }}</span>
                <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
                <button @click="changePage(totalPages)" :disabled="currentPage === totalPages">末页</button>
            </div>
        </div>

        <!-- 统计信息 -->
        <div class="stats-panel">
            <h3>论坛统计</h3>
            <div class="stat-item">
                <span>总帖子数: {{ stats.totalPosts }}</span>
            </div>
            <div class="stat-item">
                <span>总用户数: {{ stats.totalUsers }}</span>
            </div>
            <div class="stat-item">
                <span>今日新帖: {{ stats.todayPosts }}</span>
            </div>
            <div class="stat-item">
                <span>在线用户: {{ stats.onlineUsers }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue'  // 删除 computed
import { useRouter } from 'vue-router'
import {
    getForumCategories,
    getForumPosts,
    likePost,
    favoritePost,
    getForumStats,
    searchForumPosts
} from '@/api/forumApi'

export default {
    name: 'ForumIndex',
    setup() {
        const router = useRouter()
        const categories = ref([])
        const posts = ref([])
        const stats = ref({})
        const currentCategoryId = ref(null)
        const currentPage = ref(1)
        const pageSize = ref(10)
        const totalPages = ref(1)
        const searchKeyword = ref('')
        const loading = ref(false)

        // 获取板块列表
        const fetchCategories = async () => {
            try {
                const res = await getForumCategories()
                categories.value = res.data
            } catch (error) {
                console.error('获取板块列表失败:', error)
            }
        }

        // 获取帖子列表
        const fetchPosts = async () => {
            loading.value = true
            try {
                const params = {
                    sectionId: currentCategoryId.value,
                    page: currentPage.value,
                    pageSize: pageSize.value,
                    order: 'latest'
                }
                const res = await getForumPosts(params)
                posts.value = res.data.items
                totalPages.value = Math.ceil(res.data.total / pageSize.value)
            } catch (error) {
                console.error('获取帖子列表失败:', error)
            } finally {
                loading.value = false
            }
        }

        // 获取统计数据
        const fetchStats = async () => {
            try {
                const res = await getForumStats()
                stats.value = res.data
            } catch (error) {
                console.error('获取统计数据失败:', error)
            }
        }

        // 切换板块
        const switchCategory = (categoryId) => {
            currentCategoryId.value = categoryId
            currentPage.value = 1
            fetchPosts()
        }

        // 切换页码
        const changePage = (page) => {
            currentPage.value = page
            fetchPosts()
        }

        // 点赞/取消点赞
        const toggleLike = async (postId) => {
            try {
                await likePost(postId)
                // 更新本地状态
                const post = posts.value.find(p => p.id === postId)
                if (post) {
                    post.isLiked = !post.isLiked
                    post.likeCount = post.isLiked ? post.likeCount + 1 : post.likeCount - 1
                }
            } catch (error) {
                console.error('点赞操作失败:', error)
            }
        }

        // 收藏/取消收藏
        const toggleFavorite = async (postId) => {
            try {
                await favoritePost(postId)
                // 更新本地状态
                const post = posts.value.find(p => p.id === postId)
                if (post) {
                    post.isFavorited = !post.isFavorited
                }
            } catch (error) {
                console.error('收藏操作失败:', error)
            }
        }

        // 搜索帖子
        const handleSearch = async () => {
            if (!searchKeyword.value.trim()) {
                fetchPosts()
                return
            }

            loading.value = true
            try {
                const res = await searchForumPosts(searchKeyword.value, {
                    categoryId: currentCategoryId.value,
                    page: 1,
                    pageSize: pageSize.value
                })
                posts.value = res.data.items
                totalPages.value = Math.ceil(res.data.total / pageSize.value)
                currentPage.value = 1
            } catch (error) {
                console.error('搜索帖子失败:', error)
            } finally {
                loading.value = false
            }
        }

        // 创建新帖
        const createNewPost = () => {
            router.push({ name: 'CreatePost' })
        }

        // 格式化日期
        const formatDate = (dateString) => {
            const date = new Date(dateString)
            return date.toLocaleString()
        }

        // 初始化
        onMounted(() => {
            fetchCategories()
            fetchPosts()
            fetchStats()
        })

        return {
            categories,
            posts,
            stats,
            currentCategoryId,
            currentPage,
            totalPages,
            searchKeyword,
            loading,
            switchCategory,
            changePage,
            toggleLike,
            toggleFavorite,
            handleSearch,
            createNewPost,
            formatDate
        }
    }
}
</script>

<style scoped>
/* 样式省略，可以根据实际需求添加 */
</style>